import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_common_app/data/user_info_data.dart';
import 'package:flutter_common_app/provider_model/user_model.dart';
import 'package:flutter_common_app/utils/common_util/log_util.dart';
import 'package:flutter_common_app/utils/common_util/shared_preferences/sp_keys_constant.dart';
import 'package:flutter_common_app/utils/common_util/shared_preferences/sp_util.dart';
import 'package:provider/provider.dart';

class UserUtil {
  static bool isLogin(BuildContext context) {
    String cookie = getUserInfo(context)?.cookie ?? '';
    return cookie != null && cookie.isNotEmpty;
  }

  static void logout(BuildContext context) {
    LogUtil.v('----logout----');
    updateUserModel(context,UserInfoData());
    SpUtil.remove(SpKeysConstant.cookie);
  }

  static String getCookie(BuildContext context) {
    return getUserInfo(context)?.cookie ?? '';
  }

  static void setSpUserInfo(Map<String, dynamic> userInfoData) {
    SpUtil.setString(SpKeysConstant.userInfo, jsonEncode(userInfoData));
  }

  static Future<String> getSpUserInfo() async {
    return await SpUtil.getString(SpKeysConstant.userInfo);
  }

  static UserInfoData getUserInfo(BuildContext context) {
    return Provider.of<UserModel>(context, listen: false).userInfoData;
  }

  static void updateUserModel(BuildContext context,UserInfoData userInfoData) {
    Provider.of<UserModel>(context, listen: false)
        .updateUserInfoData(userInfoData);
  }
}
